package com.fl.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class KillController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/placeorder")
    public boolean getUser(HttpServletRequest request) {


        String commodity = request.getParameter("commodity");//获取商品编号
        System.out.println(commodity);
        if (commodity == null || !"101 102 103".contains(commodity)) return false;//商品号不存在


        long orderNum = System.currentTimeMillis();//获取当前的时间戳当做订单号


//判断该订单号是否已经成功下单
        boolean temp = stringRedisTemplate.opsForSet().isMember("orderNum", orderNum + "");//如果订单号已经购买成功
        if (temp) return true;


        stringRedisTemplate.setEnableTransactionSupport(true);//开启事务的支持
        stringRedisTemplate.watch("num" + commodity);//watch某个key,当该key被其它客户端改变时,则会中断当前的操作


        String numTemp = stringRedisTemplate.opsForValue().get("num" + commodity);
        if (numTemp == null) return false;
        long num = Long.valueOf(numTemp);//获取当前商品的数量
        if (num <= 0) {//检查当前商品的数量
            stringRedisTemplate.opsForList().leftPush("state", "订单号=" + orderNum + "----商品编号=" + commodity + "----秒杀已结束");
            return false;
        }
        stringRedisTemplate.multi();//事务
        stringRedisTemplate.boundValueOps("num" + commodity).decrement(1);//下单成功 商品数量减1
        stringRedisTemplate.opsForSet().add("orderNum", orderNum + "");
        List<Object> exec = stringRedisTemplate.exec();//执行事务
        if (exec == null || exec.size() == 0) {
            stringRedisTemplate.opsForList().leftPush("state", "订单号=" + orderNum + "----商品编号=" + commodity + "----秒杀失败");
            return false;
        } else {
            stringRedisTemplate.opsForList().leftPush("state", "订单号=" + orderNum + "----商品编号=" + commodity + "----秒杀成功");
            return true;//成功秒杀商品
        }
    }
}
